package com.m7.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author likai
 * @date 2020/4/19 2:16
 * @email likai@7moor..com
 * @desc
 */
public class WebSocketConnect implements Runnable{

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketConnect.class);


    private String url;

    private int connections;

    public WebSocketConnect(String url,int connections) {
        this.url = url;
        this.connections=connections;
    }

    private AtomicInteger connection = new AtomicInteger();


    @Override
    public void run() {
        try {
            connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void connect() throws Exception {
        URI uri = new URI(url);
        EventLoopGroup group = new NioEventLoopGroup(2);
        try {
            long beginTime = System.currentTimeMillis();
            for(int i=0;i<connections;i++) {
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioSocketChannel.class)
                        .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true)
                        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast(
                                        new HttpClientCodec(),
                                        new HttpObjectAggregator(8192),
                                        WebSocketClientCompressionHandler.INSTANCE,
                                        new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(
                                                uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())));
                            }
                        });
                WebSocketClientHandshaker webSocketClientHandshaker = WebSocketClientHandshakerFactory.newHandshaker(
                        uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders());


                Channel channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
                WebSocketClientHandler webSocketClientHandler = channel.pipeline().get(WebSocketClientHandler.class);
                webSocketClientHandler.setHandshaker(webSocketClientHandshaker);
                webSocketClientHandshaker.handshake(channel);

                ChannelFuture channelFuture = webSocketClientHandler.handshakeFuture().sync();
                channelFuture.addListener(new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture future) throws InterruptedException {
                        if (future.isSuccess()) {
                            LOGGER.info(future.channel().id() +
                                    " connect successfully. current connected count:" + connection.incrementAndGet());
                        } else {
                            LOGGER.error(future.channel().id() + "connect failed. current connected count:" + connection.get());
                        }
                    }
                });
                //Thread.sleep(1000L);
            }
            LOGGER.info("finished connect.");
            LOGGER.info("连接耗时时长：{}",Performance.getConsuming());
            LOGGER.info("执行时间：ms:{}",(System.currentTimeMillis()-beginTime));
            while (true) {
                Thread.sleep(5000);
            }

        }catch (Exception e){
            LOGGER.error("连接异常：{}",e);
        } finally{
            group.shutdownGracefully();
        }
    }
}
